package com.modbus.tcp.controller;

import com.modbus.tcp.util.ModbusMasterTCPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lxd
 * @Date: 2022/11/7 18:07
 */

@Slf4j
@RestController
@RequestMapping("/modbus-tcp")
public class ModbusTcpController {

    @Value("${modbus-tcp.host}")
    private String host;

    @Value("${modbus-tcp.port}")
    private int port;

    @Value("${modbus-tcp.unitId}")
    private int unitId;


    @GetMapping("/send/{address}/{quantity}")
    public Object modbusTcpSend(@PathVariable("address") Integer address, @PathVariable("quantity") Integer quantity) {
        List<Object> result = new ArrayList<>();
        try {
            ModbusMasterTCPUtils.init(host, port);
            result.add(ModbusMasterTCPUtils.readHoldingRegisters(address, quantity, unitId));
        } catch (Exception ex) {
            log.error("tcp发送出错", ex);
        }
        return result;
    }

    @GetMapping("/write/{address}/{value}")
    public Object modbusTcpWrite(@PathVariable("address") Integer address, @PathVariable("value") Integer value) {
        List<Object> result = new ArrayList<>();

        try {
            ModbusMasterTCPUtils.init(host, port);
            ModbusMasterTCPUtils.writeHoldingRegisters(address, value, unitId);
        } catch (Exception ex) {
            log.error("tcp发送出错", ex);
        }
        return result;
    }


}
